import pandas as pd
import os
import shutil

def copy_file(src_path, dest_path):
    """
    将文件从源路径复制到目标路径

    参数:
        src_path: 源文件的完整路径（包括文件名）
        dest_path: 目标路径（可以是目录或完整的目标文件路径）

    返回:
        bool: 复制成功返回True，失败返回False
    """
    try:
        # 检查源文件是否存在
        if not os.path.isfile(src_path):
            print(f"错误：源文件不存在 - {src_path}")
            return False

        # 检查目标目录是否存在，不存在则创建
        dest_dir = os.path.dirname(dest_path)
        if dest_dir and not os.path.exists(dest_dir):
            os.makedirs(dest_dir, exist_ok=True)
            print(f"已创建目标目录 - {dest_dir}")

        # 复制文件（保留元数据）
        shutil.copy2(src_path, dest_path)
        print(f"文件已成功复制：\n从 {src_path}\n到 {dest_path}")
        return True

    except Exception as e:
        print(f"复制文件失败：{str(e)}")
        return False

for result_label in ["annualized_shape", "margin",
                     "information_ratio", "calmar_ratio"]:
    df = pd.read_csv('result/backtest_result_heatmap.csv')
    # tmp_df = df[[f"{result_label}","window", "k"]]
    tmp_df = df.dropna(subset=[f"{result_label}"])
    tmp_df.sort_values(by=[f"{result_label}"], ascending=False, inplace=True)
    concat_df = pd.concat([tmp_df[:3], tmp_df[-3:]])

    for colummn in ["annualized_shape", "annualized_return", "annualized_volatility", "turnover", "margin",
                         "fitness", "max_drawdown", "information_ratio", "calmar_ratio", "trading_counts",
                         "winning_rate", "profit_loss_ratio"]:
        concat_df[colummn] = concat_df[colummn].astype(float).apply(lambda x: f"{x:.4f}")
    concat_df.to_csv(f'top3/{result_label}.csv', index=False)
    count = 1
    for index, row in concat_df.iterrows():
        oi_l = row['oi_l']
        oi_s = row['oi_s']
        png_path = f"png/oi_l={oi_l},oi_s={oi_s}.png"
        value = row[f'{result_label}']
        copy_file(png_path, f"top3/{result_label}_{count}={value},{count}_oi_l={oi_l},oi_s={oi_s}.png")
        count += 1
